package com.example.administrator.yuejian35.Me.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.administrator.yuejian35.Config;
import com.example.administrator.yuejian35.Find.GlideLoader;
import com.example.administrator.yuejian35.Find.activity.AddPostActivity;
import com.example.administrator.yuejian35.Home.bean.Result;
import com.example.administrator.yuejian35.MainActivity;
import com.example.administrator.yuejian35.Me.MeModel;
import com.example.administrator.yuejian35.Me.bean.UserInfo;
import com.example.administrator.yuejian35.R;

import com.example.administrator.yuejian35.RoundTransform;
import com.justin.bieber.city.city.CityPickerView;
import com.justin.bieber.city.city.bean.CityBean;
import com.justin.bieber.city.city.bean.DistrictBean;
import com.justin.bieber.city.city.bean.ProvinceBean;
import com.justin.bieber.image.ImageConfig;
import com.justin.bieber.image.ImageSelector;
import com.justin.bieber.image.ImageSelectorActivity;
import com.squareup.picasso.Picasso;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import de.hdodenhof.circleimageview.CircleImageView;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class UserUpDataActivity extends AppCompatActivity {

    private TextView submit,citys;
    private EditText name,sex,tel,intro;
    private ImageButton back;
    private ImageView userpic;
    private ArrayList<String> path = new ArrayList<>();

    private String up_name,up_sex,up_tel,up_city,up_intro,Uid;

    public static final int REQUEST_CODE = 123;

    private ImageConfig imageConfig;


    private Context context;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_up_data);

        name = (EditText) findViewById(R.id.updata_uname);
        sex = (EditText) findViewById(R.id.updata_sex);
        tel = (EditText) findViewById(R.id.updata_years);
        intro = (EditText) findViewById(R.id.updata_intro);
        citys = (TextView) findViewById(R.id.updata_city);
        submit = (TextView) findViewById(R.id.updata_submit);
        userpic = (ImageView) findViewById(R.id.updata_userpic);
        back = (ImageButton) findViewById(R.id.updata_btn_back);

        MainActivity mainActivity = new MainActivity();
        if (mainActivity != null) {
            Uid = mainActivity.getUserId();
        }

        Log.v("uid", Uid);

        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        UsersInfo();

        userpic.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                imageConfig = new ImageConfig.Builder(
                        new GlideLoader())
                        .steepToolBarColor(getResources().getColor(R.color.titleBlue))
                        .titleBgColor(getResources().getColor(R.color.titleBlue))
                        .titleSubmitTextColor(getResources().getColor(R.color.white))
                        .titleTextColor(getResources().getColor(R.color.white))
                        // 开启多选   （默认为多选）
                        .mutiSelect()
                        // 多选时的最大数量   （默认 9 张）
                        .mutiSelectMaxSize(1)
                        //设置图片显示容器，参数：、（容器，每行显示数量，是否可删除）
//                        .setContainer(llContainer, 1, true)
                        // 已选择的图片路径
                        .pathList(path)
                        // 拍照后存放的图片路径（默认 /temp/picture）
                        .filePath("/temp")
                        // 开启拍照功能 （默认关闭）
                        .showCamera()
                        .requestCode(REQUEST_CODE)
                        .build();
                ImageSelector.open(UserUpDataActivity.this, imageConfig);
            }
        });

        citys.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                CityPickerView cityPicker = new CityPickerView.Builder(UserUpDataActivity.this).textSize(20)
                        .titleTextColor("#000000")
                        .backgroundPop(0xa0000000)
                        .province("江苏省")
                        .city("南京市")
                        .district("秦淮区")
                        .textColor(Color.parseColor("#000000"))
                        .provinceCyclic(true)
                        .cityCyclic(false)
                        .districtCyclic(false)
                        .visibleItemsCount(7)
                        .itemPadding(10)
                        .build();
                cityPicker.show();
                cityPicker.setOnCityItemClickListener(new CityPickerView.OnCityItemClickListener() {

                    @Override
                    public void onCancel() {

                    }

                    @Override
                    public void onSelected(ProvinceBean province, CityBean city, DistrictBean district) {
                        citys.setText(
                                 province.getName() + "  " + city.getName() + "   " + district.getName());
                    }
                });
            }
        });


        submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                UpdataSubmit();
            }
        });



    }

    private void UsersInfo() {
        MeModel memodel = new MeModel();
        Call<UserInfo> call = memodel.userinfo(Uid);

        call.enqueue(new Callback<UserInfo>() {
            @Override
            public void onResponse(Call<UserInfo> call, Response<UserInfo> response) {
               UserInfo user = response.body();
                name.setText(user.getUname());
                tel.setText(user.getTel());
                intro.setText(user.getIntro());
                citys.setText(user.getAddress());
                if(user.getSex().equals("1")){
                    sex.setText("男");
                }
                else {
                    sex.setText("女");
                }

                if(!user.getUserpic().equals("")){
                    Picasso.with(context)
                            .load(Config.CoachImages_URL+user.getUserpic())
                            .transform(new RoundTransform(100))
                            .into(userpic);
                }


            }

            @Override
            public void onFailure(Call<UserInfo> call, Throwable t) {

            }
        });

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE && resultCode == RESULT_OK && data != null) {
            List<String> pathList = data.getStringArrayListExtra(ImageSelectorActivity.EXTRA_RESULT);

            path.clear();
            path.addAll(pathList);

            File file = new File(path.get(0));
            if (file.exists()) {
                Bitmap bm = BitmapFactory.decodeFile(path.get(0));
                //将图片显示到ImageView中
                userpic.setImageBitmap(bm);
            }

        }
    }

    private void UpdataSubmit() {
        up_city = String.valueOf(citys.getText());
        up_intro = String.valueOf(intro.getText());
        up_name = String.valueOf(name.getText());
        //up_sex = String.valueOf(sex.getText());
        up_tel = String.valueOf(tel.getText());
        if(String.valueOf(sex.getText()).equals("男")){
            up_sex = "1";
        }
        else{
            up_sex = "0";
        }

        if(path.size() > 0){
            File file = new File(path.get(0));

            RequestBody requestFile =
                    RequestBody.create(MediaType.parse("multipart/form-data"), file);


            MultipartBody.Part body =
                    MultipartBody.Part.createFormData("pic", file.getName(), requestFile);

            MeModel memodel = new MeModel();
            Call call = memodel.editusers(Uid,up_name,up_intro,up_sex,up_tel,up_city,body);

            call.enqueue(new Callback<Result>() {
                @Override
                public void onResponse(Call<Result> call, Response<Result> response) {
                    Toast.makeText(UserUpDataActivity.this,"修改成功！！！",Toast.LENGTH_SHORT).show();
                    finish();
                }

                @Override
                public void onFailure(Call<Result> call, Throwable t) {
                    Toast.makeText(UserUpDataActivity.this,"联网失败！！！",Toast.LENGTH_SHORT).show();
                }
            });

        }

        else{
            MeModel memodel = new MeModel();
            Call call = memodel.edituser(Uid,up_name,up_intro,up_sex,up_tel,up_city);

            call.enqueue(new Callback<Result>() {
                @Override
                public void onResponse(Call<Result> call, Response<Result> response) {
                    Toast.makeText(UserUpDataActivity.this,"修改成功！！！",Toast.LENGTH_SHORT).show();
                    finish();
                }

                @Override
                public void onFailure(Call<Result> call, Throwable t) {
                    Toast.makeText(UserUpDataActivity.this,"联网失败！！！",Toast.LENGTH_SHORT).show();
                }
            });
        }



    }


}
